import rpcAPI from "./rpcAPI";

const http = require('http');
const url = require('url');


const server = http.createServer((req, res) => {
    const { pathname } = url.parse(req.url);
    if (pathname !== '/jsonrpc') {
        res.end(JSON.stringify({ error: 'Invalid JSON-RPC' }));
    }

  if (req.method === 'POST') {
    let body = '';
    req.on('data', (chunk) => {
      body += chunk.toString();
    });

    req.on('end', () => {
      res.setHeader('Content-Type', 'application/json');
      try {
        const requestData = JSON.parse(body);
        if (requestData.jsonrpc !== "2.0") {
          res.statusCode = 400;
          res.end(JSON.stringify({ error: 'Invalid JSON-RPC version' }));
          return
        }
        const responseData = handleRequest(requestData);
        res.end(JSON.stringify(responseData));
      } catch (error) {
        res.statusCode = 400;
        res.end(JSON.stringify({ error: 'Invalid JSON' }));
      }
    });
  } else if (req.method === 'OPTIONS') {

    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
    res.end();
  } else {
    res.statusCode = 405;
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify({ error: 'Method Not Allowed' }));
  }
});


function handleRequest(requestData) {

  switch (requestData.method) {
    case 'sayHello':
      return { result: `Hello, ${requestData.params.name}!` };
    default:
      return rpcAPI.RunFunc(requestData.method, requestData.params);
  }
}

export default server;
